package com.example.contentprovider;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class EditActivity extends AppCompatActivity {
    private EditText et_id, et_name, et_price, et_description;
    private Button bt_sc, bt_tj;
    private ImageView iv_img;
    private String id;
    private Bitmap bitmap;

    public static int ALBUM_RESULT_CODE = 0x999;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);
        Intent intent = getIntent();
        BitmapUtil bitmapUtil = new BitmapUtil();
        id = intent.getStringExtra("ID");
        String name = intent.getStringExtra("NAME");
        int price = intent.getIntExtra("PRICE", 0);
        String description = intent.getStringExtra("DESCRIPTION");
//        Bitmap img = (Bitmap) intent.getParcelableExtra("IMG");
        Bitmap img = bitmapUtil.getBitmapFromFile("IMG");


        bt_sc = findViewById(R.id.bt_sc);
        iv_img = findViewById(R.id.iv_img);
        et_id = findViewById(R.id.et_id);
        et_name = findViewById(R.id.et_name);
        et_price = findViewById(R.id.et_price);
        bt_tj = findViewById(R.id.bt_tj);
        et_description = findViewById(R.id.et_description);

        et_id.setText(id);
        et_name.setText(name);
        et_price.setText(String.valueOf(price));
        et_description.setText(description);
        iv_img.setImageBitmap(img);

        bt_tj.setOnClickListener(view -> {
            Uri uri = Uri.parse("content://com.gdcp.demo/fruit");
            ContentValues values = new ContentValues();
            values.put("name", et_name.getText().toString());
            values.put("price", Integer.parseInt(et_price.getText().toString()));
            values.put("description",et_description.getText().toString());
            ByteArrayOutputStream baos= new ByteArrayOutputStream();
            Bitmap bit= bitmap;
            bit.compress(Bitmap.CompressFormat.PNG,100,baos);
            byte[] i=baos.toByteArray();
            values.put("img",i);
            String where = "id='" + id+"'";
            int rows = getContentResolver().update(uri,values,where,null);
            finish();
        });

        if (ActivityCompat.checkSelfPermission(EditActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(EditActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    1);
        }

        bt_sc.setOnClickListener(view -> {
            Intent albumIntent = new Intent(Intent.ACTION_PICK);
            albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(albumIntent, ALBUM_RESULT_CODE);

        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        handleImageOnKitKat(data);
    }

    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content: //downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        // 根据图片路径显示图片
        displayImage(imagePath);
        System.out.println(imagePath);
    }

    @SuppressLint("Range")
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {

            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(String imagePath) {
        bitmap = BitmapFactory.decodeFile(imagePath);
        iv_img.setImageBitmap(bitmap);
    }

}